﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DIProject.Dictionary
{
    public partial class NewAssortment : Form
    {
        private Int32 GetCount
        {
            get
            {
                string QueryString =
@"select count(id)
FROM   CA.Assortment
where name like '%' + @r + '%'
AND (ToDelete = 0 OR ToDelete = @ToDelete)
";
                using (SqlConnection connection = new SqlConnection(this.conStr))
                {
                    SqlCommand command = new SqlCommand(QueryString, connection);
                    SqlParameter r = new SqlParameter("@r", SqlDbType.VarChar, 50);
                    r.Value = this.Filtr;
                    command.Parameters.Add(r);
                    r = new SqlParameter("@ToDelete", Data.Sync.IsAdmin);
                    command.Parameters.Add(r);
                    connection.Open();
                    object obj = command.ExecuteScalar();
                    if (Convert.IsDBNull(obj) || obj == null)
                        return 0;
                    return Convert.ToInt32(obj);
                }
            }
        }
        private string conStr
        {
            get
            {
                return Properties.Settings.Default.DIAptekaConnectionString;
            }
        }
        private string Filtr
        {
            get
            {
                string str = txbFiltr.Text;
                if (string.IsNullOrEmpty(str))
                    return string.Empty;
                return str;
            }
        }
        List<Int32> _data = new List<int>();
        public NewAssortment()
        {
            InitializeComponent();
        }
        private List<Int32> GetData(string flr)
        {
            string QueryString =
           @"
SELECT     Id
FROM   CA.Assortment
where name like '%' + @r + '%'
AND (ToDelete = 0 OR ToDelete = @ToDelete)
ORDER BY Name";
            List<Int32> res = new List<int>();
            using (SqlConnection connection = new SqlConnection(this.conStr))
            {
                SqlCommand command = new SqlCommand(QueryString, connection);
                SqlParameter r = new SqlParameter("@r", SqlDbType.VarChar, 50);
                r.Value = flr;
                command.Parameters.Add(r);
                r = new SqlParameter("@ToDelete", Data.Sync.IsAdmin);
                command.Parameters.Add(r);
                connection.Open();
                SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
                Int32 i2 = dr.GetOrdinal("ID");
                while (dr.Read())
                {
                    Int32 tmp = dr.GetInt32(i2);
                    res.Add(tmp);
                }
            }
            return res;
        }
        DataSets.NewDist.AssortmentRow rTmp = null;
        Int32 iTmp = Int32.MinValue;
        DataSets.NewDistTableAdapters.AssortmentTableAdapter adapter = new DIProject.DataSets.NewDistTableAdapters.AssortmentTableAdapter();
        private DataSets.NewDist.AssortmentRow GetOneRow(Int32 goodId)
        {
            if (goodId == iTmp)
                return rTmp;
            DataSets.NewDist.AssortmentDataTable tb = adapter.GetData(goodId);
            if (tb.Count == 0)
                return null;
            rTmp = tb.Rows[0] as DataSets.NewDist.AssortmentRow;
            iTmp = goodId;
            return rTmp;
        }

        private void dgv_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            Int32 ri = e.RowIndex;
            Int32 ci = e.ColumnIndex;
            Int32 gId = _data[ri];
            DataSets.NewDist.AssortmentRow gl = this.GetOneRow(gId);
            if (gl == null)
                return;
            e.Value = gl[dgv.Columns[ci].DataPropertyName];
            DataSets.NewDistTableAdapters.QueriesTableAdapter ad = new DIProject.DataSets.NewDistTableAdapters.QueriesTableAdapter();
            
        }

        private void txbFiltr_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dgv.Rows.Clear();
                dgv.RowCount = this.GetCount;
                _data = this.GetData(this.Filtr);
                txbFiltr.SelectAll();
            }
        }

        private void NewAssortment_Load(object sender, EventArgs e)
        {
            dgv.RowCount = this.GetCount;
            _data = this.GetData(this.Filtr);
        }
       public Int32 SelectedId
        {
            get
            {
                if (dgv.SelectedRows.Count < 1)
                    return Int32.MinValue;
                return (Int32)dgv.SelectedRows[0].Cells[0].Value;
            }
        }
        public string SelectedName
        {
            get
            {
                if (dgv.SelectedRows.Count < 1)
                    return string.Empty;
                return (string)dgv.SelectedRows[0].Cells[1].Value;
            }
        }
        DataSets.NewDist.AssortmentRow CurrentRow
        {
            get
            {
                if (SelectedId == Int32.MinValue)
                    return null;
                DataSets.NewDist.AssortmentDataTable dt = adapter.GetData(this.SelectedId);
                if (dt.Rows.Count < 1)
                    return null;
                return dt.Rows[0] as DataSets.NewDist.AssortmentRow;
            }
        }
        private void delButton_Click(object sender, EventArgs e)
        {
            if (dgv.SelectedRows.Count < 1)
            {
                MessageBox.Show("Нужно выбрать строку");
                return;
            }
            DataSets.NewDist.AssortmentRow tmp = this.CurrentRow;
            string mw = FirstForm.Login;
            if(Data.Sync.IsAdmin)
                mw = "PhysicallyDelete";
            Data.Assortment.DeleteAssortment(tmp.Id, tmp.MD, mw);
            MessageBox.Show("Запись успешно удалена");
            dgv.Rows.Clear();
            dgv.RowCount = this.GetCount;
            _data = this.GetData(this.Filtr);
            txbFiltr.SelectAll();

        }

        private void addButton_Click(object sender, EventArgs e)
        {
            
            NewAssortmentDetails nad = new NewAssortmentDetails(Util.ActionType.Insert, null);
            DialogResult dr = nad.ShowDialog();
            if (dr == DialogResult.OK)
            {
                dgv.Rows.Clear();
                dgv.RowCount = this.GetCount;
                _data = this.GetData(this.Filtr);
                txbFiltr.SelectAll();
            }
            nad.Close();
        }

        private void modifiButton_Click(object sender, EventArgs e)
        {
            if (dgv.SelectedRows.Count < 1)
            {
                MessageBox.Show("Нужно выбрать строку");
                return;
            }
            NewAssortmentDetails nad = new NewAssortmentDetails(Util.ActionType.Update, this.SelectedId);
            DialogResult dr = nad.ShowDialog();
            if (dr == DialogResult.OK)
            {
                dgv.Rows.Clear();
                dgv.RowCount = this.GetCount;
                _data = this.GetData(this.Filtr);
                txbFiltr.SelectAll();
            }
            nad.Close();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
        
    }
}